package com.zbf.auth.login;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zbf.auth.dao.UserDao;
import com.zbf.auth.service.MenuService;
import com.zbf.auth.user.User;
import com.zbf.common.entity.ResponseResult;
import com.zbf.common.entity.ResponseResultEnum;
import com.zbf.common.utils.*;

import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 作者: LCG
 * 日期: 2020/5/31 17:33
 * 描述: 登录实现类
 */

@RestController
public class LoginController {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private MenuService menuService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private TwitterIdWorker twitterIdWorker;
    /**
     * 登录实现
     * @return
     */
    @RequestMapping("/login")
    public ResponseResult toLogin(@RequestBody User puser){

        if(puser.getLoginName()!=null&&!puser.getLoginName().equals("")){
            //根据登录名获取用户
            User user = userDao.findByLoginNameIs(puser.getLoginName());
            //如果用户不存在
            if(user==null){
                ResponseResult responseResult = ResponseResult.getResponseResult();
                responseResult.setCode(ResponseResultEnum.FAILURE.getCode());
                responseResult.setError(ResponseResultEnum.FAILURE.getMessage());
                return responseResult;
            }else{
                //校验用户是不是激活
                if(user.getActive()==0){
                    ResponseResult responseResult = ResponseResult.getResponseResult();
                    responseResult.setCode(ResponseResultEnum.FAILURE.getCode());
                    responseResult.setError(ResponseResultEnum.FAILURE.getMessage());
                    return responseResult;
                }

                //如果用户存在则校验密码的正确性
                String password = MD5.encryptPassword(puser.getPassWord(), user.getSalt());
                if(password.equals(user.getPassWord())){
                    ResponseResult responseResult = ResponseResult.getResponseResult();
                    responseResult.setCode(ResponseResultEnum.SECCESS.getCode());
                    responseResult.setError(ResponseResultEnum.SECCESS.getMessage());

                    //使用Jwt对登录信息进行加密
                    String token = JWTUtis.generateToken(JSON.toJSONString(user));
                    //将用户信息存入Redis
                    String userInfoId="USERINFO"+user.getId().toString();
                    redisTemplate.delete(userInfoId);
                    redisTemplate.opsForValue().set(userInfoId,token);
                    //设置一天的过期时间
                    redisTemplate.expire(userInfoId,1,TimeUnit.DAYS);
                    //查询用户的权限信息存入Redis
                    Map<String, Object> userMenuInfo = menuService.getUserMenuInfo(user.getId());
                    Map<String,String> menuUrlMap =(Map<String,String>)userMenuInfo.get("menuUrlMap");
                    //缓存用户的权限信息
                    String authUrlId="AUTHURL"+user.getId().toString();
                    redisTemplate.delete(authUrlId);
                    redisTemplate.opsForHash().putAll(authUrlId,menuUrlMap);
                    //设置一天的过期时间
                    redisTemplate.expire(authUrlId,1,TimeUnit.DAYS);
                    //for gc
                    menuUrlMap=null;
                    //缓存用户的menu列表
                    String authMenuId="AUTHMENU"+user.getId().toString();
                    redisTemplate.delete(authMenuId);
                    redisTemplate.opsForValue().set(authMenuId,JSON.toJSONString(userMenuInfo.get("userMenuList")));
                    //设置一天的过期时间
                    redisTemplate.expire(authMenuId,1,TimeUnit.DAYS);
                    //for gc
                    userMenuInfo=null;
                    //将Token信息返回给前端
                    responseResult.setToken(token);
                    //将用户信息返回前端
                    user.setPassWord("");
                    user.setSalt("");
                    String userInfo=JSON.toJSONString(user);
                    JSONObject jsonObject = JSON.parseObject(userInfo);
                    jsonObject.put("userId",user.getId().toString());
                    responseResult.setUserInfo(jsonObject);
                    return responseResult;
                }else{
                    ResponseResult responseResult = ResponseResult.getResponseResult();
                    responseResult.setCode(ResponseResultEnum.FAILURE.getCode());
                    responseResult.setError(ResponseResultEnum.FAILURE.getMessage());
                    return responseResult;
                }
            }
        }else{
            //用户不存在
            ResponseResult responseResult = ResponseResult.getResponseResult();
            responseResult.setCode(ResponseResultEnum.FAILURE.getCode());
            responseResult.setError(ResponseResultEnum.FAILURE.getMessage());
            return responseResult;
        }

    }



    /**
     * 注册信息
     * @return
     */
    @RequestMapping("/toRegister")
    public ResponseResult toRegister(@RequestBody User user){

        //加密密码
        String salt= UID.getUUID16();
        user.setPassWord(MD5.encryptPassword(user.getPassWord(),salt));
        //设置ID
        user.setId(twitterIdWorker.nextId());
        //设置盐值
        user.setSalt(salt);
        //设置创建时间
        user.setCreateTime(new Date());
        //设置版本
        user.setVersion(10L);
        //设置激活状态
        user.setActive(0);
        //注册信息
        User user1 = userDao.saveAndFlush(user);
        //返回注册信息
        ResponseResult responseResult = ResponseResult.getResponseResult();
        if (user1.getId()!=0){
            //使用线程池向邮箱发送邮件
            Map<String,Long> map=new HashMap<>();
            map.put("userId",user1.getId());
            String linkedHerf="http://localhost:10000/sso/auth/toActive?code="+JWTUtis.generateTokenForActive(JSON.toJSONString(map),24*60*60*1000L);
            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    Mail126Utils.sendMail(user.getMail(),"三斗网络",linkedHerf);
                }
            });
            responseResult.setSuccess(ResponseResultEnum.REGISTER.getMessage());
            responseResult.setCode(ResponseResultEnum.REGISTER.getCode());
        }else{
            responseResult.setSuccess(ResponseResultEnum.FAILURE.getMessage());
            responseResult.setCode(ResponseResultEnum.FAILURE.getCode());
        }

        return responseResult;
    }

}
